home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9869 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: wkaufman.us.oracle.com!wkaufman
  2. From: wkaufman@wkaufman.us.oracle.com (William Kaufman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Determining the length of an int in string form
  5. Date: 14 Mar 1996 02:05:37 GMT
  6. Organization: Oracle Corporation, Redwood Shores CA
  7. Message-ID: <4i7uth$qph@inet-nntp-gw-1.us.oracle.com>
  8. References: <3146D058.DD7@cbm.com>
  9. NNTP-Posting-Host: wkaufman.us.oracle.com
  10.  
  11. In article <3146D058.DD7@cbm.com> Dave Payne <paynedc@cbm.com> writes:
  12. ] Consider this:
  13. ] I have a variable of type int, and I would like to use the sprintf() 
  14. ] function to write this variable to a string.  However, I want to 
  15. ] dynamically allocate the space for the string, and only malloc enough 
  16. ] space to hold the int.
  17.  
  18.     For any binary number, the number of decimal digits is about 0.3 the
  19. number of binary digits.  (It's actually log10(2), but 0.3 is close
  20. enough.)  So, for an int, that's about
  21.  
  22.         int i;
  23.  
  24.         (sizeof(i) * CHAR_BIT * 10) / 3
  25.  
  26. (For maximum accuracy, use ints, multiply first, then divide.)
  27.  
  28.     Add in a character for the "-" sign, and another for the '\0' at the
  29. end, and maybe another one just for the fact that I rounded log10(2)
  30. down to 0.3, and you'll have overshot by about a character, since I
  31. didn't account for the fact that it's a signed quantity and the maximum
  32. is a bit smaller than (sizeof(int) * CHAR_BIT).  But, hey, what's a
  33. character between friends?
  34.  
  35.     The nice thing about the above calculation is that it's an integral
  36. constant: you can even use it in an array declaration.
  37.  
  38.     If you want it to perfectly match the integer you've got, rather
  39. than any integer you may get, you could do something like
  40. (size_t)(log10((double)i)) and add in the extra characters listed above.
  41. (Mind you, I'm not convinced that the extra time calling log10() is
  42. worth saving a few bytes per string--depending on how many strings
  43. you've got.)
  44.  
  45.                                            -- Bill K.
  46.  
  47. Bill Kaufman,          | "Patience is a virtue.  Seersucker is a fabric."
  48. wkaufman@us.oracle.com |                                   -- Bazooka Joe
  49.